package com.grade.controller;

import com.grade.Beans.Student;
import com.grade.Beans.Teacher;
import com.grade.service.Impl.TeacherServiceImpl;
import com.grade.service.TeacherService;
import com.grade.utils.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController  {
    private final TeacherServiceImpl teacherService;

    public TeacherController(TeacherServiceImpl teacherService) {
        this.teacherService = teacherService;
    }

    @RequestMapping("/login")
    @ResponseBody
    public Results login(String userName, String password , String code, HttpSession session){
        String Systemcode=(String)session.getAttribute("systemCode");
        if (code == null) {
            return new Results<>("4", "请输入验证码");
        }
        if (Systemcode == null) {
            return new Results<>("4", "验证码已过期，请刷新");
        }
        if (!code.equalsIgnoreCase(Systemcode)) {
            return new Results<>("4", "验证码错误");
        }
        if(code.equalsIgnoreCase(Systemcode)){
            Teacher teacher=teacherService.login(userName,password);
            if(teacher !=null)
            {
                session.setAttribute("usr",userName);
                return  new Results("0","登录成功");
            }
            else{
                System.out.println("登录失败");
                return new Results("1","账号或密码错误");
            }
        }else{
            return new Results<>("4","验证码错误");
        }
    }
    @RequestMapping("/updatePwd")
    @ResponseBody
    public Results updatePwd(String pwd, String pwd1, String pwd2, HttpSession session) {
        // 1. 非空校验，避免空指针异常
        if (pwd == null || pwd1 == null || pwd2 == null) {
            return new Results("1", "密码不能为空");
        }

        // 2. 获取当前登录教师姓名
        String tname = (String) session.getAttribute("usr");
        if (tname == null) {
            return new Results("1", "请先登录");
        }

        // 3. 验证两次新密码是否一致
        if (!pwd1.equals(pwd2)) {
            return new Results("2", "两次输入的新密码不同");
        }

        // 4. 验证原密码是否正确（新增必要步骤）
        Teacher teacher = teacherService.login(tname,pwd);
        if (teacher == null) {
            return new Results("3", "原密码不正确");
        }

        // 5. 执行密码更新
        int count = teacherService.updatepassword(tname, pwd1);
        if (count > 0) {
            // 6. 密码修改成功后建议清除session，强制重新登录
            session.invalidate();
            return new Results("0", "密码修改成功");
        } else {
            return new Results("1", "密码修改失败");
        }
    }

}
